import Config from '../store/index'
// #ifdef APP-PLUS
var jpushModule = uni.requireNativePlugin("JG-JPush");
// #endif

class JGPush {
	constructor() {}
	/**
	 * 极光推送
	 */
	jiGuangPush() {
		// #ifdef APP-PLUS
		jpushModule.setLoggerEnable(true);
		jpushModule.initJPushService()
		jpushModule.addConnectEventListener(result => {
			let connectEnable = result.connectEnable
			console.log("jpush连接", connectEnable)
		})
		jpushModule.addNotificationListener(result => {
			console.log("通知", result)
			let notificationEventType = result.notificationEventType
			let messageID = result.messageID
			let title = result.title
			let content = result.content
			let extras = result.extras || {}
			if (notificationEventType === 'notificationOpened') {
				let path = extras.path || '/pages/index/index'
				if (path.indexOf('/pages/index/index') != -1 ||
					path.indexOf('/pages/category/category') != -1 ||
					path.indexOf('/pages/message/message') != -1 ||
					path.indexOf('/pages/center/center') != -1) {
					uni.switchTab({
						url: path
					})
				} else if (path.indexOf('/page') != -1) {
					uni.navigateTo({
						url: path
					})
				}
			}
			console.log("通知", result)
		})
		this.getJiGuangRegistrationID()
		jpushModule.addCustomMessageListener(result => {
			let messageID = result.messageID
			let content = result.content
			let extras = result.extras || {}
			console.log("自定义消息", result)
		})
		// #endif
	}
	getJiGuangRegistrationID() {
		// #ifdef APP-PLUS
		jpushModule.getRegistrationID(result => {
			console.log("注册ID", result.registerID)
			if (result.registerID) {
				// uni.removeStorageSync('register_id')
				let jgRgId = uni.getStorageSync('register_id')
				if (jgRgId !== result.registerID) {
					uni.setStorageSync("register_id", result.registerID)
					// this.saveJiGuangId(result.registerID)
				}
			}
		})
		// #endif
	}
	jiGuangUpdateBadge(num) {
		// #ifdef APP-PLUS
		// plus.runtime.setBadgeNumber(num)
		// #endif
	}
	/**
	 * 保存极光注册ID
	 */
	saveJiGuangId(clientId) {
		return new Promise((resolve, reject) => {
			let params = {
				type: '',
				clientId
			}
			const platform = uni.getSystemInfoSync().platform
			if (platform === 'ios') {
				params.type = 2
			} else if (platform === 'android') {
				params.type = 1
			}
			let header = checkLoginObj.getLoginData() || {}
			uni.request({
				url: `${Config.API_PATH}/api/userClient/save`,
				method: 'POST',
				data: params,
				header: header.headerObject ? header.headerObject : {},
				success: (res) => {
					console.log(`${Config.API_PATH}/api/userClient/save`);
					console.log(header.headerObject ? header.headerObject : {});
					console.log(params);
					console.log(res);
				}
			})
		})
	}
}

export default new JGPush()